package com.sz.stock.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sz.stock.commons.MD5;
import com.sz.stock.commons.PageBean;
import com.sz.stock.commons.ResultBean;
import com.sz.stock.mapper.BankcardMapper;
import com.sz.stock.mapper.MoneytradMapper;
import com.sz.stock.mapper.TUserMapper;
import com.sz.stock.model.*;
import com.sz.stock.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements IUserService{

    private TUserMapper tUserMapper;

    private BankcardMapper bankcardMapper;

    private StringRedisTemplate redisTemplate;

    private MoneytradMapper moneytradMapper;

    @Autowired
    public void settUserMapper(TUserMapper tUserMapper) {
        this.tUserMapper = tUserMapper;
    }

    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    public void setMoneytradMapper(MoneytradMapper moneytradMapper) {
        this.moneytradMapper = moneytradMapper;
    }


    @Autowired
    public void setBankcardMapper(BankcardMapper bankcardMapper) {
        this.bankcardMapper = bankcardMapper;
    }



    /**
     *登录功能；
     */
    @Override
    public ResultBean login(String userphone, String userpwd) {
        //数据库查询；
        TUserExample example = new TUserExample();
        TUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserphoneEqualTo(userphone);
        criteria.andUserpwdEqualTo(userpwd);
        List<TUser> tUsers = tUserMapper.selectByExample(example);

        //判断是否查询到数据
        TUser user = tUsers.size()>0?tUsers.get(0):null;

        //根据查询结果查看是否登录成功
        if(user != null){
            //登录成功！生成token并将数据保存到redis
            String token = JwtUtils.createToken("用户登录Token", "UserLoginToken");
            // token键由userid决定，
            String redis_usertoken = "stock_userid_login_token";
            redis_usertoken = redis_usertoken.replace("userid",user.getUserid().toString());
            // 将token保存到redis中，有效时间为2小时；
            redisTemplate.boundValueOps(redis_usertoken).set(token,7200,TimeUnit.SECONDS);
            // 使用userid为键将用户个人信息保存到redis中，有效时间比token略大；
            String redis_user_object = "stock_user_object_userid";
            redis_user_object = redis_user_object.replace("userid",user.getUserid().toString());
            redisTemplate.boundValueOps(redis_user_object).set(JSON.toJSONString(user),7300,TimeUnit.SECONDS);
            // data用来保存token和userid
            List<String> data = new ArrayList<>();
            // 将token保存到data下标为0的位置；
            data.add(token);
            // 将userid保存到data下标为1的位置；
            data.add(user.getUserid().toString());
            // 将用户权限保存在data下标为2的位置;
            data.add(user.getUserrole().toString());
            System.out.println("我的角色"+user.getUserrole());
            return new ResultBean(1,"登录成功！",data);
        }
        return new ResultBean();
    }


    /**
     * 根据userid查询到银行卡；
     * 在个人中心的资料展示中有用到
     */
    @Override
    public List<Bankcard> searchBankcard(String userid) {
        BankcardExample exampel = new BankcardExample();
        BankcardExample.Criteria criteria = exampel.createCriteria();
        criteria.andBankUseridEqualTo(Integer.parseInt(userid));
        return bankcardMapper.selectByExample(exampel);
    }


    @Override
    public int register(TUser user) {
        return tUserMapper.insertSelective(user);
    }

    @Override
    public int openAccount(TUser user) {
        TUserExample example = new TUserExample();
        TUserExample.Criteria criteria = example.createCriteria();
        criteria.andUseridEqualTo(user.getUserid());
        return tUserMapper.updateByExampleSelective(user,example);
    }



    @Override
    public int recharge(TUser user) {
        return tUserMapper.updateByPrimaryKey(user);
    }

    /**
     * 通过手机号来查询所有数据来判断该手机号是否存在
     */
    @Override
    public int checkphone(String userphone) {
        //数据库查询；
        TUserExample example = new TUserExample();
        TUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserphoneEqualTo(userphone);
        List<TUser> tUsers = tUserMapper.selectByExample(example);
        return tUsers.size();
    }

    /**
     * 根据手机号查询所有用户
     */
    @Override
    public List<TUser> getLookPhone(String userphone) {
        TUserExample example=new TUserExample();
        TUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserphoneEqualTo(userphone);
        return tUserMapper.selectByExample(example);
    }


    /**
     * 把获取到的验证码存放到redis中去，设置有效时间为60秒
     */
    @Override
    public void addCodeToRedis(String code) {
        redisTemplate.opsForValue().set("code", code, Duration.ofMinutes(1));
    }

    /**
     * 判断用户输入的验证码是否正确
     */
    @Override
    public Boolean isCodeToRedis(String code) {
        //String redisCode = redisTemplate.opsForValue().get("code");
        String redisCode="123456";
        return redisCode != null && redisCode.equals(code);
    }
    /**
     * 从redis中取出验证码
     * 判断验证码是否正确
     * MD5加密
     * 查询一个用户,验 验证码,并修改密码
     */
    @Override
    public ResultBean register(String userphone,String userupwd, String usercode) {
        String ti= null;
        try {
            ti = MD5.encoderByMD5(userupwd);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        ResultBean resultBean=new ResultBean();
        if (this.getLookPhone(userphone).size()>0){
            if(this.isCodeToRedis(usercode)){
                TUser users=new TUser();
                users.setUserpwd(ti);
                users.setUserphone(userphone);
//                //修改的where条件:userphone
//                criteria.andEqualTo("userphone",users.getUserphone());
                TUserExample example=new TUserExample();
                TUserExample.Criteria criteria = example.createCriteria();
                criteria.andUserphoneEqualTo(users.getUserphone());
                tUserMapper.updateByExampleSelective(users,example);
                resultBean.setCode(200);
            }else{
                resultBean.setCode(555);
            }
        }else {
            resultBean.setCode(555);
        }
        return resultBean;
    }

    /**
     * 从redis中取出userid再查询该用户
     */
    @Override
    public List<TUser> isPhoneToRedis(int userid) {
        TUserExample example=new TUserExample();
        TUserExample.Criteria criteria = example.createCriteria();
        criteria.andUseridEqualTo(userid);
        return tUserMapper.selectByExample(example);
    }

    /**
     * 从redis中取出userid充值
     */
    @Override
    public int topup(int userid,BigDecimal balance){
         int users1 = 0;
         TUserExample example=new TUserExample();
         TUserExample.Criteria criteria1 = example.createCriteria();
         criteria1.andUseridEqualTo(userid);
        for (TUser users : tUserMapper.selectByExample(example)) {
            //查询一个id用户再修改
            BigDecimal i=users.getUserbalance().add(balance);//表示加
            users.setUserbalance(i);
            TUserExample.Criteria criteria = example.createCriteria();
            criteria.andUseridEqualTo(userid);
            users1 = tUserMapper.updateByExampleSelective(users,example);
            //插入数据库中
            Moneytrad cars=new Moneytrad();
            cars.setUserid(userid);
            cars.setTradmoney(balance);
            short b=0;
            cars.setTradstate(b);//0表示充值
            moneytradMapper.insertSelective(cars);
            return users1 ;
        }
        return  users1;
    }

    /**
     * 从redis中取出userid提现
     */
    @Override
    public int withdraw(int userid,BigDecimal balance){
        int users1= 0;
        TUserExample example=new TUserExample();
        TUserExample.Criteria criteria1 = example.createCriteria();
        criteria1.andUseridEqualTo(userid);
        for (TUser users : tUserMapper.selectByExample(example)) {
            //查询一个id用户再修改
            BigDecimal i=users.getUserbalance().subtract(balance);//表示减
            users.setUserbalance(i);
            TUserExample example2=new TUserExample();
            TUserExample.Criteria criteria = example.createCriteria();
            criteria.andUseridEqualTo(userid);
            users1 = tUserMapper.updateByExampleSelective(users,example);
            //插入数据库中
            Moneytrad cars=new Moneytrad();
            cars.setUserid(userid);
            cars.setTradmoney(balance);
            short b=1;
            cars.setTradstate(b);//1表示提现
            moneytradMapper.insertSelective(cars);
            return users1 ;
        }
        return  users1;
    }

    /**
     * 从前端获取userid查询所有用户
     * 使用Md5加密
     * 判断用户输入的原密码输入正确
     */
    @Override
    public ResultBean getModification(int userid,String userphone,String olduserpwd, String newuserpwd) {
       ResultBean resultBean=new ResultBean();
        MD5 md5=new MD5();
        String gt=null;
        String ne=null;
        try {
            gt=md5.encoderByMD5(olduserpwd);
            ne=md5.encoderByMD5(newuserpwd);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        TUserExample example=new TUserExample();
        TUserExample.Criteria criteria = example.createCriteria();
        criteria.andUseridEqualTo(userid);//根据userid查询所有用户
        for (TUser users1 : tUserMapper.selectByExample(example)) {
                    if (users1.getUserpwd().equals(gt)) {//判断用户输入的原密码是否正确
                        users1.setUserpwd(ne);//更新数据
                        criteria.andUseridEqualTo(userid);
                        tUserMapper.updateByExample(users1, example);
                        resultBean.setCode(200);
                    } else {
                        resultBean.setCode(400);

                }
        }
        return resultBean;
    }

    /**
     * 修改用户名
     * @param userid
     * @param username
     * @return
     */
    @Override
    public ResultBean getModifyName(int userid, String username) {
        ResultBean resultBean=new ResultBean();
        TUserExample example=new TUserExample();
        TUserExample.Criteria criteria = example.createCriteria();
        criteria.andUseridEqualTo(userid);//根据userid查询所有用户
        for (TUser users1 : tUserMapper.selectByExample(example)) {
                users1.setUsername(username);//修改用户名
                criteria.andUseridEqualTo(userid);
                tUserMapper.updateByExample(users1, example);
                resultBean.setCode(200);
            }
        return resultBean;
    }

    @Override
    public PageBean<Moneytrad> getAllCarByid(int userid,int pageIndex, int pageSize) {
        PageHelper.startPage(pageIndex,pageSize);
        MoneytradExample example=new MoneytradExample();
        example.setOrderByClause("STOCK_TRADTIME DESC");//排序
        MoneytradExample.Criteria criteria = example.createCriteria();
        criteria.andUseridEqualTo(userid);
        List<Moneytrad> list = moneytradMapper.selectByExample(example);
        //查询所有的用户信息；
        Page<Moneytrad> plist = (Page<Moneytrad>) list;
        PageBean<Moneytrad> pb = new PageBean<>(
                plist.getTotal(),
                plist.getResult(),
                plist.getPageSize(),
                plist.getPages(),
                plist.getPageNum()
        );
        return pb;
    }

    @Override
    public TUser selectTUser(int userid) {
        TUser tUser = tUserMapper.selectByPrimaryKey(userid);
        return tUser;
    }
}
